<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>购买订单 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
    <style>
        /* 推荐商品模块样式 */
        .recommend-container {
            margin-top: 30px;
            padding: 20px 0;
        }
        .recommend-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .recommend-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        .refresh-btn {
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 5px 10px;
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        .refresh-btn:hover {
            background-color: #e9e9e9;
        }
        .refresh-btn svg {
            margin-right: 5px;
            width: 16px;
            height: 16px;
        }
        .recommend-list {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
        }
        .recommend-item {
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 10px;
            text-decoration: none;
            color: inherit;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .recommend-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .recommend-img {
            width: 100%;
            height: 140px;
            object-fit: cover;
            border-radius: 4px;
            margin-bottom: 8px;
        }
        .recommend-name {
            font-weight: bold;
            margin-bottom: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .recommend-price {
            color: #e74c3c;
            font-weight: bold;
        }

        @media (max-width: 768px) {
            .recommend-list {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        /* 添加模态框和关闭按钮的样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            overflow: auto;
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px 40px;
            border: 1px solid #888;
            width: 80%;
            max-width: 500px;
            border-radius: 8px;
            position: relative;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        .close {
            position: absolute;
            top: 10px;
            right: 10px;
            color: #333;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            background: #f1f1f1;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            display: block;
            z-index: 1001;
        }

        .close:hover {
            background-color: #ddd;
            color: #000;
        }

        /* 修改卡片样式，避免覆盖关闭按钮 */
        #contactModal .card {
            margin-top: 15px;
            padding-top: 15px;
        }
    </style>
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section class="fade-in">
        <h2>购买订单</h2>
        <div class="card">
            <div id="orderList"></div>
        </div>

        <div class="mt-20">
            <h3>评价订单</h3>
            <div id="reviewForm" class="hidden">
                <div class="card">
                    <input type="hidden" id="reviewOrderId">
                    <div class="form-group">
                        <label for="descriptionScore">商品描述评分:</label>
                        <select id="descriptionScore">
                            <option value="5">5 - 非常满意</option>
                            <option value="4">4 - 满意</option>
                            <option value="3" selected>3 - 一般</option>
                            <option value="2">2 - 不满意</option>
                            <option value="1">1 - 非常不满意</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="responseScore">卖家响应速度评分:</label>
                        <select id="responseScore">
                            <option value="5">5 - 非常满意</option>
                            <option value="4">4 - 满意</option>
                            <option value="3" selected>3 - 一般</option>
                            <option value="2">2 - 不满意</option>
                            <option value="1">1 - 非常不满意</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="reviewComment">评价内容:</label>
                        <textarea id="reviewComment" rows="3"></textarea>
                    </div>
                    <div class="flex">
                        <button id="submitReviewBtn" class="btn">提交评价</button>
                        <button id="cancelReviewBtn" class="btn secondary">取消</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="mt-20">
            <div id="contactModal" class="modal">
                <div class="modal-content">
                    <span class="close" id="closeContactModal">&times;</span>
                    <h3 style="margin-top: 5px; margin-bottom: 15px; text-align: center; padding-top: 10px;">卖家联系方式</h3>
                    <div class="card">
                        <p id="sellerUsername"></p>
                        <p id="sellerPhone"></p>
                    </div>
                    <div style="text-align: center; margin-top: 15px;">
                        <button id="closeContactBtn" class="btn" onclick="hideContactModal()">关闭</button>
                    </div>
                </div>
            </div>
        </div>

        <div id="msg" class="mt-20"></div>

        <!-- 推荐商品模块 -->
        <div class="recommend-container">
            <div class="recommend-header">
                <h3 class="recommend-title">你可能感兴趣的商品</h3>
                <button id="refreshRecommendBtn" class="refresh-btn">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M23 4v6h-6"></path>
                        <path d="M1 20v-6h6"></path>
                        <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10"></path>
                        <path d="M20.49 15a9 9 0 0 1-14.85 3.36L1 14"></path>
                    </svg>
                    刷新推荐
                </button>
            </div>
            <div id="recommendList" class="recommend-list">
                <!-- 推荐商品将在这里动态加载 -->
            </div>
        </div>
    </section>
</div>
<script>
    // 页面加载时确保评价表单隐藏
    document.addEventListener('DOMContentLoaded', function() {
        hideReviewForm();
        loadRecommendProducts(); // 加载推荐商品
    });

    async function loadOrders() {
        try {
            // 确保评价表单隐藏
            hideReviewForm();

            const res = await fetch('/api/orders', {
                credentials: 'include'
            });
            const data = await res.json();

            if (!data || data.length === 0) {
                document.getElementById('orderList').innerHTML = '<p class="text-center">暂无订单</p>';
                return;
            }

            let html = '<table><tr><th>订单号</th><th>商品名称</th><th>数量</th><th>价格</th><th>状态</th><th>下单时间</th><th>操作</th></tr>';

            for (const order of data) {
                const statusMap = {
                    'pending': '待处理',
                    'accepted': '已接单',
                    'shipped': '待收货',
                    'completed': '已完成',
                    'cancelled': '已取消',
                    'reviewed': '已评价'
                };

                const statusClass = {
                    'pending': 'status-pending',
                    'accepted': 'status-shipped',
                    'shipped': 'status-shipped',
                    'completed': 'status-completed',
                    'cancelled': 'status-cancelled',
                    'reviewed': 'status-reviewed'
                };

                const statusText = statusMap[order.status] || order.status;
                const statusClassName = statusClass[order.status] || '';
                const productName = order.product ? order.product.name : '未知商品';

                // 开始操作按钮容器
                let actionButtons = '<div class="order-actions">';

                // 根据状态添加不同的按钮和active类
                if (order.status === 'pending') {
                    actionButtons += `<button onclick="cancelOrder(${order.id})" class="btn warning active">取消</button>`;
                } else {
                    actionButtons += `<button class="btn warning">取消</button>`;
                }

                if (order.status === 'shipped') {
                    actionButtons += `<button onclick="confirmReceived(${order.id})" class="btn success active">确认收货</button>`;
                } else {
                    actionButtons += `<button class="btn success">确认收货</button>`;
                }

                if (order.status === 'completed') {
                    actionButtons += `<button onclick="showReviewForm(${order.id})" class="btn active">评价</button>`;
                } else if (order.status === 'reviewed') {
                    actionButtons += `<button onclick="showReviewForm(${order.id})" class="btn active">修改评价</button>`;
                } else {
                    actionButtons += `<button class="btn">评价</button>`;
                }

                // 删除按钮和联系卖家按钮始终可用
                actionButtons += `<button onclick="confirmDelete(${order.id})" class="btn delete-btn active">删除</button>`;
                actionButtons += `<button onclick="contactSeller(${order.id})" class="btn contact-btn active">联系卖家</button>`;

                actionButtons += '</div>'; // 结束操作按钮容器

                html += `<tr>
                <td>${order.id}</td>
                <td>${productName}</td>
                <td>${order.quantity}</td>
                <td>¥${order.totalPrice}</td>
                <td><span class="status-tag ${statusClassName}">${statusText}</span></td>
                <td>${new Date(order.createdAt).toLocaleString()}</td>
                <td>${actionButtons}</td>
            </tr>`;
            }

            html += '</table>';
            document.getElementById('orderList').innerHTML = html;
        } catch (e) {
            console.error('加载订单失败:', e);
            document.getElementById('orderList').innerHTML = '<p class="error-msg">请先登录</p>';
        }
    }

    async function cancelOrder(orderId) {
        try {
            // 确保评价表单隐藏
            hideReviewForm();

            document.getElementById('msg').innerHTML = '<div class="info-msg">正在取消订单...</div>';

            const res = await fetch(`/api/orders/${orderId}/status?status=cancelled`, {
                method: 'POST',
                credentials: 'include'
            });
            const data = await res.json();

            if (data.id) {
                document.getElementById('msg').innerHTML = '<div class="success-msg">订单已取消</div>';
                loadOrders();
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '操作失败'}</div>`;
            }
        } catch (e) {
            document.getElementById('msg').innerHTML = '<div class="error-msg">操作失败</div>';
        }
    }

    async function confirmReceived(orderId) {
        try {
            // 确保评价表单隐藏
            hideReviewForm();

            document.getElementById('msg').innerHTML = '<div class="info-msg">正在确认收货...</div>';

            const res = await fetch(`/api/orders/${orderId}/status?status=completed`, {
                method: 'POST',
                credentials: 'include'
            });
            const data = await res.json();

            if (data.id) {
                document.getElementById('msg').innerHTML = '<div class="success-msg">已确认收货</div>';
                loadOrders();
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '操作失败'}</div>`;
            }
        } catch (e) {
            document.getElementById('msg').innerHTML = '<div class="error-msg">操作失败</div>';
        }
    }

    function confirmDelete(orderId) {
        // 确保评价表单隐藏
        hideReviewForm();

        if (confirm('是否确认删除此订单？')) {
            deleteOrder(orderId);
        }
    }

    async function deleteOrder(orderId) {
        try {
            document.getElementById('msg').innerHTML = '<div class="info-msg">正在删除订单...</div>';

            const res = await fetch(`/api/orders/${orderId}`, {
                method: 'DELETE',
                credentials: 'include'
            });

            const data = await res.json();

            if (data.success) {
                document.getElementById('msg').innerHTML = '<div class="success-msg">订单已删除</div>';
                loadOrders(); // 重新加载订单列表
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '删除失败，请重试'}</div>`;
            }
        } catch (e) {
            console.error('删除订单失败:', e);
            document.getElementById('msg').innerHTML = '<div class="error-msg">删除失败，请重试</div>';
        }
    }

    // 设置模态框关闭按钮事件
    document.getElementById('closeContactModal').addEventListener('click', hideContactModal);

    // 显示联系卖家模态框
    function showContactModal() {
        document.getElementById('contactModal').style.display = 'block';
    }

    // 隐藏联系卖家模态框
    function hideContactModal() {
        document.getElementById('contactModal').style.display = 'none';
    }

    async function contactSeller(orderId) {
        try {
            // 确保评价表单隐藏
            hideReviewForm();

            console.log(`获取订单信息: ${orderId}`);
            document.getElementById('msg').innerHTML = '<div class="info-msg">正在获取卖家联系方式...</div>';

            const res = await fetch(`/api/orders/${orderId}`, {
                credentials: 'include'
            });

            console.log('API响应状态:', res.status);

            if (res.ok) {
                const order = await res.json();
                console.log('订单数据:', order);

                if (order && order.product && order.product.user) {
                    const seller = order.product.user;
                    console.log('卖家信息:', seller);

                    document.getElementById('sellerUsername').innerHTML = `<strong>用户名:</strong> ${seller.username || '未知用户'}`;
                    document.getElementById('sellerPhone').innerHTML = `<strong>电话号码:</strong> ${seller.phoneNumber || '未提供'}`;
                    showContactModal();
                    document.getElementById('msg').innerHTML = '';
                } else {
                    console.error('卖家信息不完整:', order);
                    document.getElementById('msg').innerHTML = '<div class="error-msg">无法获取卖家信息，数据不完整</div>';
                }
            } else {
                console.error('获取订单失败:', res.status);
                document.getElementById('msg').innerHTML = '<div class="error-msg">获取订单信息失败</div>';
            }
        } catch (e) {
            console.error('获取卖家联系方式失败:', e);
            document.getElementById('msg').innerHTML = '<div class="error-msg">获取卖家联系方式失败</div>';
        }
    }

    function showReviewForm(orderId) {
        document.getElementById('reviewForm').classList.remove('hidden');
        document.getElementById('reviewOrderId').value = orderId;

        // 如果是修改评价，尝试获取现有评价数据
        fetchExistingReview(orderId);
    }

    function hideReviewForm() {
        document.getElementById('reviewForm').classList.add('hidden');
        document.getElementById('reviewOrderId').value = '';
        document.getElementById('reviewComment').value = '';
        document.getElementById('descriptionScore').value = '3';
        document.getElementById('responseScore').value = '3';
    }

    async function fetchExistingReview(orderId) {
        try {
            // 尝试通过订单ID获取评价
            const res = await fetch(`/api/reviews/order/${orderId}`, {
                credentials: 'include'
            });

            if (res.ok) {
                const review = await res.json();
                if (review && review.id) {
                    // 填充表单数据
                    document.getElementById('descriptionScore').value = review.descriptionScore;
                    document.getElementById('responseScore').value = review.responseScore;
                    document.getElementById('reviewComment').value = review.comment || '';
                }
            }
        } catch (e) {
            console.error('获取评价数据失败:', e);
        }
    }

    document.getElementById('submitReviewBtn').onclick = async () => {
        const orderId = document.getElementById('reviewOrderId').value;
        const descriptionScore = parseInt(document.getElementById('descriptionScore').value);
        const responseScore = parseInt(document.getElementById('responseScore').value);
        const comment = document.getElementById('reviewComment').value;

        try {
            document.getElementById('msg').innerHTML = '<div class="info-msg">正在提交评价...</div>';

            const res = await fetch(`/api/reviews/order/${orderId}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({
                    descriptionScore,
                    responseScore,
                    comment
                })
            });

            const data = await res.json();
            if (data.id) {
                document.getElementById('msg').innerHTML = '<div class="success-msg">评价成功</div>';
                hideReviewForm();
                loadOrders(); // 重新加载订单列表，更新状态
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '评价失败'}</div>`;
            }
        } catch (e) {
            document.getElementById('msg').innerHTML = '<div class="error-msg">评价失败</div>';
        }
    };

    // 添加取消按钮事件处理
    document.getElementById('cancelReviewBtn').onclick = () => {
        hideReviewForm();
    };

    // 加载推荐商品
    async function loadRecommendProducts() {
        try {
            const res = await fetch('/api/products/recommend?limit=4', {
                credentials: 'include'
            });
            const products = await res.json();

            if (!products || products.length === 0) {
                document.getElementById('recommendList').innerHTML = '<p class="text-center">暂无推荐商品</p>';
                return;
            }

            let html = '';
            for (const product of products) {
                // 处理图片URL
                let imageUrl = product.imageUrl;
                if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                    imageUrl = '/' + imageUrl;
                }

                html += `
                <a href="/product-detail?id=${product.id}" class="recommend-item">
                    <img src="${imageUrl || ''}"
                         class="recommend-img"
                         alt="${product.name}"
                         onerror="
                            if(!this.retried) {
                                this.retried = true;
                                // 尝试使用不同的路径格式
                                let newSrc = '${product.imageUrl || ''}';
                                if(newSrc && newSrc.startsWith('/')) {
                                    newSrc = newSrc.substring(1);
                                } else if(newSrc) {
                                    newSrc = '/' + newSrc;
                                }
                                this.src = newSrc;
                            } else {
                                this.onerror = null;
                                this.src = '';
                            }
                         ">
                    <div class="recommend-name">${product.name}</div>
                    <div class="recommend-price">¥${product.price}</div>
                </a>
            `;
            }

            document.getElementById('recommendList').innerHTML = html;
        } catch (e) {
            console.error('加载推荐商品失败:', e);
            document.getElementById('recommendList').innerHTML = '<p class="text-center">加载推荐商品失败</p>';
        }
    }

    // 刷新推荐按钮点击事件
    document.getElementById('refreshRecommendBtn').addEventListener('click', function() {
        loadRecommendProducts();
    });

    // 页面加载时加载订单
    loadOrders();

    // 确保DOM加载完成后添加事件监听
    document.addEventListener('DOMContentLoaded', function() {
        // 重新绑定关闭按钮事件，确保事件监听器正确添加
        document.getElementById('closeContactModal').addEventListener('click', hideContactModal);
        if (document.getElementById('closeContactBtn')) {
            document.getElementById('closeContactBtn').addEventListener('click', hideContactModal);
        }
    });
</script>
</body>
</html> 